﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Macaw.Spf2010.ResourceListSolution
{
    /// <summary>
    /// 
    /// </summary>
    public class ResourceListReader
    {
        /// <summary>
        /// Static name of the field of the ResourceList which holds the Key values
        /// </summary>
        private static string KeyColumnName = "Title";

        /// <summary>
        /// Name of the default ResourceList.
        /// </summary>
        private const string DEFAULTLISTNAME = "ResourceList";

        /// <summary>
        /// Retrieves the configuration value for a specific key
        /// </summary>
        /// <param name="configurationKey">The key for the resourcelist,  with which a value can be retrieved</param>
        /// <param name="configurationListName">The name of the resourcelist</param>
        /// <returns>The value matching a given key, or empty string otherwise</returns>
        public static String GetValue(String Key, string ListName, string ColName)
        {
            LoggingService.WriteTrace(LoggingService.Categories.ResourceListReader, Microsoft.SharePoint.Administration.TraceSeverity.Verbose, "GetValue: Key \"{0}\", List \"{1}\", ColName \"{2}\"", new string[] { Key, ListName, ColName });

            if (SPContext.Current == null)
            {
                LoggingService.WriteEvent(LoggingService.Categories.ResourceListReader, Microsoft.SharePoint.Administration.EventSeverity.Warning, "SPContext.Current is null. Unable to GetValue of ResourceList");
                return string.Empty;
            }

            String returnValue = String.Empty;
            SPList configurationList = null;

            #region Get ResourceList
            try
            {
                if (string.IsNullOrEmpty(ListName))
                {
                    if (SPContext.Current.Site.RootWeb.Properties.ContainsKey("ResourceList"))
                    {
                        string configurationListUrl = SPUrlUtility.CombineUrl(SPContext.Current.Site.ServerRelativeUrl, SPContext.Current.Site.RootWeb.Properties["ResourceList"]);
                        configurationList = SPContext.Current.Site.RootWeb.GetList(configurationListUrl);
                    }
                    else
                    {
                        configurationList = SPContext.Current.Site.RootWeb.Lists[DEFAULTLISTNAME];
                    }
                }
                else
                {
                    configurationList = SPContext.Current.Site.RootWeb.Lists[ListName];
                }
            }
            catch (Exception ex)
            {
                LoggingService.WriteEvent(LoggingService.Categories.ResourceListReader, Microsoft.SharePoint.Administration.EventSeverity.Error, "GetValue: Key \"{0}\", List \"{1}\", ColName \"{2}\", Exception \"{3}\"", new string[] { Key, ListName, ColName, ex.ToString() });
                return returnValue;
            }
            #endregion

            #region Retrieve ListItem by Key
            String caml = String.Format("<Where><Eq><FieldRef Name='{1}'></FieldRef><Value Type='Text'>{0}</Value></Eq></Where>", Key, KeyColumnName);
            SPQuery query = new SPQuery();
            query.Query = caml;
            SPListItemCollection queryResults = configurationList.GetItems(query);
            #endregion

            #region Get Value from result
            switch (queryResults.Count)
            {
                case 0:
                    LoggingService.WriteEvent(LoggingService.Categories.ResourceListReader, Microsoft.SharePoint.Administration.EventSeverity.Warning, "GetValue: No value for Key \"{0}\", List \"{1}\", ColName \"{2}\"", new string[] { Key, ListName, ColName });
                    break;
                case 1:
                    try
                    {
                        if (SPContext.Current != null)
                        {
                            object obj = null; ;

                            if (string.IsNullOrEmpty(ColName))
                            {
                                // TwoLetterIsoLanguageName is NON capitols ad nl, en, du
                                ColName = SPContext.Current.Web.Locale.TwoLetterISOLanguageName;
                            }
                            obj = queryResults[0][ColName];
                            if (obj != null) returnValue = obj.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggingService.WriteEvent(LoggingService.Categories.ResourceListReader, Microsoft.SharePoint.Administration.EventSeverity.Warning, "GetValue: Error retrieving value for Key \"{0}\", List \"{1}\", ColName \"{2}\", Exception \"{3}\"", new string[] { Key, ListName, ColName, ex.ToString() });
                    }
                    break;
                default:
                    LoggingService.WriteEvent(LoggingService.Categories.ResourceListReader, Microsoft.SharePoint.Administration.EventSeverity.Warning, "GetValue: Multiple matches for Key \"{0}\", List \"{1}\", ColName \"{2}\"", new string[] { Key, ListName, ColName });
                    break;
            }
            #endregion

            return returnValue;
        }
    }
}
